package com.itlaobing.dataaccess.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BooleanHandler implements TypeHandler<Boolean> {

    @Override
    public void setParameter(PreparedStatement ps , int index, Boolean booleanValue, JdbcType jdbcType) throws SQLException {
        String value = booleanValue ? "Y" : "N" ;
        ps.setString( index , value );
    }

    @Override
    public Boolean getResult(ResultSet rs, String label) throws SQLException {
        String s = rs.getString( label );
        if( s != null && s.length() > 0 ) {
            s = s.toUpperCase() ;
            char value = s.charAt( 0 );
            return value == 'Y' ;
        }
        return false ;
    }

    @Override
    public Boolean getResult(ResultSet rs, int index) throws SQLException {
        String s = rs.getString( index );
        if( s != null && s.length() > 0 ) {
            s = s.toUpperCase() ;
            char value = s.charAt( 0 );
            return value == 'Y' ;
        }
        return false ;
    }

    @Override
    public Boolean getResult(CallableStatement cs, int index) throws SQLException {
        String s = cs.getString( index );
        if( s != null && s.length() > 0 ) {
            s = s.toUpperCase() ;
            char value = s.charAt( 0 );
            return value == 'Y' ;
        }
        return false ;
    }
}
